﻿using System;
using System.Collections.Generic;
using System.Linq;
using MartinRL.ProjectEuler.Sequences;

namespace MartinRL.ProjectEuler
{
    /// <summary>
    /// http://projecteuler.net/index.php?section=problems&id=23
    /// </summary>
    public static class Problem023
    {
        const int MAX_TERM = 28123;

        public static int FindTheSumOfAllThePositiveIntegersWhichCannotBeWrittenAsTheSumOfTwoAbundantNumbers()
        {
            var oneToMaxTerm = 1.To(MAX_TERM) ;

            var abundants = oneToMaxTerm.Where(IsAbundant);
             
            var allSumsOfTwoAbundants = CalculateAllSumsOfTwo(abundants);

            return oneToMaxTerm
                .Where(t => !t.In(allSumsOfTwoAbundants))
                .Sum();
        }

        private static ISet<int> CalculateAllSumsOfTwo(IEnumerable<int> sequence)
        {
            ISet<int> allSumsOfTwo = new HashSet<int>();

            var sequenceAsArray = sequence.ToArray();

            for (var i = 0; i < sequenceAsArray.Length - 2; i++)
            {
                for (var j = i; j < sequenceAsArray.Length - 1; j++)
                {
                    var sum = sequenceAsArray[i] + sequenceAsArray[j];

                    if (sum <= MAX_TERM)
                    {
                        allSumsOfTwo.Add(sum);
                    }
                }
            }

            return allSumsOfTwo;
        }

        public static bool IsAbundant(int term)
        {
            return term.SumOfProperDivisors() > term;
        }
    }
}